package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @program: heima-leadnews
 * @description: 登录
 * @author: Mr.Gu
 * @create: 2021-08-08 21:54
 **/
@Service
@Transactional
public class UserLoginServiceImpl  extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //参数校验,判断用户名或密码是否为空
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");
         }

        //查询数据库中用户信息
        /*Wrapper wrapper = new QueryWrapper<AdUser>();
        ((QueryWrapper) wrapper).eq("name", dto.getName());*/
        List<AdUser> list = list(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (list != null && list.size() == 1){
            AdUser aduser = list.get(0);
            //比对密码
            String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + aduser.getSalt()).getBytes());
            if (aduser.getPassword().equals(pwd)){
                //返回数据jwt
                HashMap<Object, Object> map = Maps.newHashMap();
                //不将此信息返回给用户,设置为空???
                aduser.setPassword("");
                aduser.setSalt("");
                map.put("token", AppJwtUtil.getToken(aduser.getId().longValue()));
                map.put("user",aduser);
                return ResponseResult.okResult(map);
            }else {
                //密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }
    }
}
